var router = require('express').Router();
var util = require('util');
var EventProxy = require('eventproxy');

var Consts = require('../consts');
var resultJson = require('../result-json');
var Utils = require('../utils');
var logger = require('../models/logger');
var BroadCast = require('../models/BroadCast');

router.post('/', function(req, res) {
	res.send('respond with a resource');
});

//查询平台公告
router.post('/list', function(req, res) {
	var broadCast = req.body;
	var proxy = new EventProxy();
	proxy.all("results", "count", function(results, count) {
		res.send(resultJson(0, {
			results: results,
			count: count
		}))
	})
	var start = broadCast.start || 0;
	var count = broadCast.count || Consts.MAX;
	BroadCast.find({}, {
		__v: 0
	}).sort({
		create: -1
	}).skip(start).limit(count).exec(function(err, broadCasts) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		proxy.emit("results", broadCasts);
	});
	BroadCast.count(function(err, num) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		proxy.emit("count", num);
	});
});

//添加或修改平台公告　
router.post('/upsert', function(req, res) {
	var broadCast = req.body;
	broadCast = JSON.stringify(broadCast);
	broadCast = broadCast.replace(/\</g, '&lt;').replace(/\>/g, '&gt;').replace(/</g, '&lt;').replace(/>/g, '&lg;');
	broadCast = JSON.parse(broadCast);
	if (!broadCast.content || !broadCast.title)
		return res.send(resultJson(3));
	if (broadCast._id) { //update
		BroadCast.update({
			_id: broadCast._id
		}, {
			$set: broadCast
		}).exec(function(err) {
			if (err) {
				logger.error(err);
				return res.send(resultJson(2));
			}
			res.send(resultJson(0));
		});
	} else { //add
		broadCast.create = new Date();
		new BroadCast(broadCast).save(function(err, broadCast) {
			if (err) {
				logger.error(err);
				return res.send(resultJson(2));
			}
			res.send(resultJson(0, broadCast));
		});
	}

});

//平台公告详情
router.post('/detail', function(req, res) {
	var broadCast = req.body;
	BroadCast.findOne({
		_id: broadCast._id
	}).exec(function(err, broadCast) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		res.send(resultJson(0, broadCast));
	});

});

//删除公告
router.post('/remove', function(req, res) {
	var broadCast = req.body;
	BroadCast.remove({
		_id: broadCast._id
	}, function(err) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		res.send(resultJson(0));
	})
});

module.exports = router;